package model.textchatserver;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import model.roomManagement.Implementation.Server;

public class TChatSocketDistributor implements Runnable
{
	private ServerSocket serverSocket;
	private static TChatSocketDistributor instance;
	
	private TChatSocketDistributor()
	{
		try
		{
			serverSocket = new ServerSocket( 7575 );
			Thread thread = new Thread( this );
			thread.start();
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	private void distribute( Socket socket )
	{
		try
		{
			BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
			String connectInfo = in.readLine();
			
		
			
			int roomId = Integer.valueOf( connectInfo );
			
			BufferedWriter responseWriter = new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) );
			responseWriter.write( "Connected Successfully！\n" );
			responseWriter.flush();
			
			
			RoomTChatSocketsManager RTCSM = Server.getRoomTCSocketManager( roomId );
			RTCSM.addNewSocket( socket );
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		} 
	}

	@Override
	public void run()
	{
		
		
		while( true )
		{
			try 
			{
				Socket socket = serverSocket.accept();
				distribute( socket );
			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}

	}
	
	public static TChatSocketDistributor getInstance()
	{
		if ( instance == null )
		{
			instance = new TChatSocketDistributor();
		}
		
		return instance;
	}
	
}
